package nl.tue.be.ds.duraark.bSDD.dump;


import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Callable;

import javax.ws.rs.core.MediaType;
import nl.tue.be.ds.duraark.bSDD.ClientUtilities;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;


public class RelSearchPerGuidCallable implements Callable<HashMap<String, String>> {
	
	private String searchConceptGuid;
	private String relationString;
	private static String relSearchUrl = "http://bsddpilot.catenda.no/api/4.0/IfdConcept/";

	public RelSearchPerGuidCallable(String searchConceptGuid, String relationString) {
		
		this.searchConceptGuid = searchConceptGuid;
		this.relationString = relationString;
	}
	
	public HashMap<String, String> call() throws Exception {
		
		HashMap<String, String> conceptInRelGuidType = searchRelationships(relSearchUrl + searchConceptGuid + "/" +relationString);
		return conceptInRelGuidType;
	}

	public HashMap<String, String> searchRelationships(String searchString) throws Exception {
		String result = null;
		HashMap<String, String> GuidTypePairs = new HashMap<String, String>();
		
		Client client = ClientUtilities.getClient();
		WebResource searchCall = client.resource(searchString);			
		result = searchCall.accept(MediaType.APPLICATION_JSON_TYPE).cookie(ClientUtilities.cookie).get(String.class);

		if (result.equalsIgnoreCase("null") == false) {
			ObjectMapper mapper = ClientUtilities.getMapper();
			JsonNode root = mapper.readTree(result);
			JsonNode jsonConceptsInRel = root.get("IfdConceptInRelationship");
				
			if (jsonConceptsInRel.isArray()) {
				Iterator<JsonNode> iterator = jsonConceptsInRel.iterator();
				while (iterator.hasNext()) {
					JsonNode jsonNode = iterator.next();
					String conceptInRGuid = jsonNode.get("guid").getTextValue();
					String relationshipType = jsonNode.get("relationshipType").getTextValue();
					GuidTypePairs.put(conceptInRGuid, relationshipType);
				}
			}else{
				String conceptInRGuid = jsonConceptsInRel.get("guid").getTextValue();
				String relationshipType = jsonConceptsInRel.get("relationshipType").getTextValue();
				GuidTypePairs.put(conceptInRGuid, relationshipType);
			}
		}else{
			GuidTypePairs = null;
		}
		return GuidTypePairs;
	}

}
